<?php
if (! defined ( 'BASEPATH' ))exit ( 'No direct script access allowed' );
/**
 * 移动端公共类
 * @author chaituan@126.com
 */
use EasyWeChat\Foundation\Application;
class WechatCommon extends CI_Controller {
	protected $User;
	protected $sf;
	protected $start = 0;
	protected $end = 0;
	protected $act_times = 0;
	function __construct() {
		parent::__construct ();
		//增加判断是否是微信
		if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') === false) {
			showmessage('请在微信手机端打开','error','#','',false);
		}elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Windows')){
			showmessage('只能在手机微信端打开','warn','#','',false);
		}
		parseURL($this->uri->segment(4));

		$this->User = $this->session->wechat_user_session; // 获取session
		$this->load->vars('U',$this->User );
		$this->check();
		//加载配置
		$this->load->vars('web_name',admin_config_cache('wechat')['wechat_name']);
	}
	
	function check() {
		if ($this->User) {
			$config = admin_config_cache('wechat');
			if($config){
				$this->load->vars('ajax',site_url('mobile/share/common'));
				$app = new Application(array('app_id'=>WX_APPID,'secret'=>WX_APPSecret));
				$this->load->vars('wxconfig',$app->js->config(array('onMenuShareTimeline','onMenuShareAppMessage','getLocation'), false));//,'hideOptionMenu','showMenuItems'
				$this->load->vars('share_data',array('title'=>$config['wechat_share_title'],'link'=>base_url($_SERVER ['REQUEST_URI']),'img'=>base_url($config['wechat_share_img']),'desc'=>$config['wechat_share_des']));
			}
		} else {			
			$url = $_SERVER ['REQUEST_URI']; // 为了从哪里进的跳转到哪里去
			$fwd = http_build_query(array('fwd' =>str_replace('.html','',$url)));
			$forward = base_url('/wechat/login/signin/?'.$fwd);
			$config = array('app_id'=>WX_APPID,'secret'=>WX_APPSecret,'oauth' => ['scopes'=> ['snsapi_userinfo'],'callback' => $forward]);
			$app = new Application($config);
			$response = $app->oauth->scopes(['snsapi_userinfo'])->redirect();			
			$response->send();
			die();
		}
	}
}

// 必须登录先
class NeedLoginAction extends WechatCommon {
	function __construct() {
		parent::__construct ();
		// 检测登录
		$this->check();
	}
}
